<?php
namespace app\api\controller;
require '../extend/jpush/autoload.php';
use app\common\controller\Api;
use think\Db;
use think\Log;

use JPush\Client as JPush;
/**
 * 系统设置接口
 */
class Site extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    //极光推送函数'1507bfd3f77f2bd3232'
    function JGPush($rid, $content,$title,$data) {
        $client = new JPush('ffb559c6e857bb14546e079d', '8352e040316b98f701de6ead');
        $client->push()
            ->setPlatform('all')
            ->addRegistrationId($rid)
            ->message('message content', array(
                'title' => $title,
                'extras' => $data,
            ))
            ->send();
    }

    public function pushtest() {
        $rid = $this->request->request('rid');
        $ganhao = $this->request->request('ganhao');
        $type = $this->request->request('type');
        $user = $this->request->request('user');
        $client = new JPush('ffb559c6e857bb14546e079d', '8352e040316b98f701de6ead');
        $result = $client->push()
            ->setPlatform('all')
            ->addRegistrationId($rid)
            ->message('信息为', array(
                'title' => '测试消息',
                'extras' => array('type' => $type,'user'=>$user,'ganhao'=>$ganhao ),
            ))
            ->send();
        if(!$result) {
            $this->error(__('推送出错'));
        }else{
            $this->success('推送成功');
        }
    }

    public function push (){
        //查询所有c端传送来的未进行推送的数据
        $app = Db::name('apptempdata')->where(['status'=>0])->select();
        Log::info('推送接口和数据===================================================');
        Log::info($app);
        foreach ($app as $key => $val) {
            
            Log::info($val);
            try {
                $msg = explode("$",$val['txt']);
                $rid = Db::query("SELECT b.`Content8` FROM `projectdata` p,`basedata` b WHERE p.`managerid`=b.`Bh` AND `Datatype` = '作业队' AND p.`Gcbh` = ?",[$val['gcbh']]);

                if($val['flag'] == 'danger'){
                    //险情信息
                    $user = Db::name('gc_pda_worker')->where(['gcbh'=>$val['gcbh'],'pdabh'=>$msg[1]])->find();
                    Log::info($user);
                    $data = array('type' => $msg[6],'user'=>$user['workername'],'ganhao'=>$msg[3] );
                    //推送
                    //$this->success('报告上传成功');
                    try {
                        $this->JGPush($rid[0]['Content8'],$msg[6],$msg[6], $data);
                        //更新状态
                        Db::name('apptempdata')->where(['id'=>$val['id']])->update(['status'=>1]);
                    } catch (Exception $e) {
                        $this->error(__('推送出错'));
                    }
                }else{
                    //地线拆除报告

                    $data = array('type' => $msg[3],'user'=>$msg[4],'ganhao'=>$msg[1] );
                    //推送
                    try {
                        Log::info($rid);
                        Log::info($msg);
                        $this->JGPush($rid[0]['Content8'],$msg[0],$msg[0], $data);
                        //更新状态
                        Db::name('apptempdata')->where(['id'=>$val['id']])->update(['status'=>1]);
                    } catch (Exception $e) {
                        $this->error(__('推送出错'));
                    }
                }
            } catch (Exception $e) {
                Log::info("推送出错");
                Log::info($val);
            }
            
        }
         $this->success('推送成功');
    }


    /**
    *获取危险信息
    */

    public function danger(){
        $gcbh = $this->request->request('gcbh');
        
        if (!$gcbh) {
            $this->error(__('Invalid parameters'));
        }
        $danger = Db::query("SELECT d.*,gpw.`workername` FROM loaclworkordangerousdata d, gc_pda_worker gpw WHERE d.`Gcbh` = ? AND gpw.`gcbh` = ? AND gpw.`pdabh` = d.`Subpdabh`",[$gcbh,$gcbh]);
        
        $this->success('获取成功', $danger);
    }


    /**
    *获取电杆挂接信息
    */

    public function linelist(){
        $gcbh = $this->request->request('gcbh');
        $types = $this->request->request('types');
        if (!$types||!$gcbh) {
            $this->error(__('Invalid parameters'));
        }
        $ganhao = Db::query("SELECT id,ganhao,jiedi,lujing FROM zuoyesubdata  WHERE Gcbh = ? AND (jiedi = 'Y' OR lujing='Y')",[$gcbh]);
        $line = Db::query("SELECT * FROM `linedata` WHERE `gcbh`=? AND linestatus = ? ORDER BY id DESC",[$gcbh,$types]);
        $data = [];
        foreach ($ganhao as $key => $value) {
            $isok = 0;
            $linetype = '';
            if($value['jiedi'] == 'Y') {
                $linetype = '许可地线';
            }else {
                $linetype = '班组地线';
            }
            foreach ($line as $key1 => $value1) {
                if($value['ganhao'] == $value1['ganhao']) {
                    $isok = 1;
                    array_push($data, array(
                        'id'=>$value['id'],
                        'linetype' => $linetype, 
                        'ganhao' => $value['ganhao'], 
                        'workerbh' => $value1['workerbh'], 
                        'linedate' => $value1['linedate'], 
                        'linetime' => $value1['linetime'], 
                        'linestatus' => $value1['linestatus'], 
                    ));
                    break;
                }
            } 
            if ($isok == 0) {
                if ($types == '拆除') {
                    $line1 = Db::query("SELECT * FROM `linedata` WHERE `gcbh`=? AND ganhao = ? AND linestatus = ? limit 1",[$gcbh,$value['ganhao'],'挂接']);
                    array_push($data, array(
                        'id'=>$value['id'],
                        'linetype' => $linetype, 
                        'ganhao' => $value['ganhao'], 
                        'workerbh' => $line1[0]['workerbh'], 
                        'linedate' => $line1[0]['linedate'] , 
                        'linetime' => $line1[0]['linetime'], 
                        'linestatus' => '挂接', 
                    ));
                }else {
                    array_push($data, array(
                        'id'=>$value['id'],
                        'linetype' => $linetype, 
                        'ganhao' => $value['ganhao'], 
                        'workerbh' => '', 
                        'linedate' => '', 
                        'linetime' => '', 
                        'linestatus' => '未操作', 
                    ));
                }

            }       
        }
        $this->success('获取成功', $data);
    }


    /**
    * 获取现场人员及终端设备明细
    */
    public function terminal_list(){
        $gcbh = $this->request->request('gcbh');
        $bh = $this->request->request('bh');
        if (!$bh||!$gcbh) {
            $this->error(__('Invalid parameters'));
        }
        $terminal_user = Db::name('gc_pda_worker')->where(['gcbh'=>$gcbh])->field('id,datatype,pdabh,workername')->select();

        //获取作业人员
        $user = Db::name('basedata')->where(['Partntid'=>$bh,'Datatype'=>'施工人员'])->field('id,Content1')->select();

        //获取终端设备
        //查询
        $aaa =Db::name('basedata')->where(['Partntid'=>$bh,'Datatype'=>'终端设备'])->field('id,Content1,Content2')->select();
        // Db::name('basedata')->where(['Partntid'=>$bh,'Datatype'=>'终端设备'])->field('id,Content1,Content2')->select();

        if(!$aaa || !$user) {
            $this->error('未获取到终端设备或工作人员');
        }
        
        foreach ($terminal_user as $key => $value) {
            foreach ($user as $key1 => $value1) {
                Log::info($value1['Content1']);
                Log::info($value['workername']);
                if($value['workername'] == $value1['Content1']){
                    unset($user[$key1]);
                }
            }
            foreach ($aaa as $key2 => $value2) {
                if($value['pdabh'] == $value2['Content2']){
                    unset($aaa[$key2]);
                }
            }
        }
        $bbb = array();
        foreach ($aaa as $key => $value) {
            # code...
            array_push($bbb, $value);
        }
        $ccc  = array();
        foreach ($user as $key => $value) {
            # code...
            array_push($ccc, $value);
        }
        $data = array(
            'terminal_user' => $terminal_user,
            'terminal' => $bbb,
            'user' => $ccc,
         );
        $this->success('获取成功', $data);
    }

    //添加进程人员
    public function add_terminal_user(){
        $gcbh = $this->request->request('gcbh');
        $uid = $this->request->request('uid');
        $tid = $this->request->request('tid');
        if (!$uid||!$gcbh||!$tid) {
            $this->error(__('Invalid parameters'));
        }

        //获取作业人员
        $user = Db::name('basedata')->where(['id'=>$uid])->find();
        //获取终端设备
        $terminal =Db::name('basedata')->where(['id'=>$tid])->find();
        if(!$user || !$terminal) {
            $this->error('未获取到终端设备或工作人员');
        }

        $terminal_user = Db::name('gc_pda_worker')->where(['gcbh'=>$gcbh,'pdabh'=> $terminal['Content2']])->find();
        if ($terminal_user) {
            $this->error('添加失败，设备已被绑定');
        }
        $terminal_user = Db::name('gc_pda_worker')->where(['gcbh'=>$gcbh,'workername'=> $user['Content1']])->find();
        if ($terminal_user) {
            $this->error('添加失败，工作人员已被绑定');
        }
        
        $id = Db::name('gc_pda_worker')->insert(['gcbh'=>$gcbh,'datatype'=>$terminal['Content1'],'pdabh'=>$terminal['Content2'],'inbh'=>'0','workerbh'=>$user['Bh'],'workername'=>$user['Content1']]); 

        $this->success('添加成功', $id);
    }
    
        //删除进程人员
    public function del_terminal_user(){
        $id = $this->request->request('id');
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        Db::table('gc_pda_worker')->where('id',$id)->delete();

        $this->success('删除成功');
    }

        /**
    * 开工申请信息
    */
    public function start_end_massage(){
        $gcbh  = $this->request->request("gcbh");
        if (!$gcbh) {
            $this->error(__('Invalid parameters'));
        }
        //获取作业点信息,
        $data = Db::query( "SELECT COUNT(xuke = 'Y' or null) as xuke,COUNT(kaiguan = 'Y' or null) as kaiguan ,COUNT(jiedi = 'Y' or null) as jiedi,COUNT(jiaokua = 'Y' or null) as jiaokua,COUNT(bingxing = 'Y' or null) as bingxing,COUNT(lujing = 'Y' or null) as lujing FROM zuoyesubdata WHERE Gcbh = ? " ,[$gcbh]);
        $inmans = Db::name('gc_pda_worker')->where(['gcbh'=>$gcbh])->select();
        $danger = Db::name('apptempdata')->where(['gcbh'=>$gcbh,'flag'=>'danger'])->select();
        $data[0]['inmans'] = count($inmans);
        $data[0]['danger'] = count($danger);
        $this->success('获取成功', $data[0]);
    }
    
    //开工申请
    public function start_end_apply(){
        $type = $this->request->request("type");
        $gcbh  = $this->request->request("gcbh");
        $jingdu = $this->request->request("jingdu");
        $weidu = $this->request->request("weidu");
        $date = $this->request->request("date");
        $time = $this->request->request("time");
        $inmans = $this->request->request("inmans");
        $kuayue = $this->request->request("kuayue");
        $weilan = $this->request->request("weilan");
        $fenglu = $this->request->request("fenglu");
        $fenghe = $this->request->request("fenghe");
        $qita = $this->request->request("qita");
        $tianqi = $this->request->request("tianqi");

        if (!$gcbh||!$type||!$jingdu||!$weidu||!$date||!$time||!$inmans||!$kuayue||!$weilan||!$fenglu||!$fenghe||!$qita||!$tianqi) {
            $this->error(__('Invalid parameters'));
        }


        $danger = Db::name('apptempdata')->where(['gcbh'=>$gcbh,'flag'=>'danger'])->select();
        $a = count($danger);
        if($a> 0) {
            $dan =strval($a) .  '-有违章';
        }else{
            $dan =strval($a) . '-无违章';
        }
        
        if ($type == '1') {
            //开工报告
            $status = '已下达开工命令';
            $sqmd = '开工';
            $gcbz = '竣';

        }else {
            $status = '已下达竣工命令';
            $sqmd = '竣工';
            $gcbz = '终';
        }
        //判断是否存在开/竣工报告
        $data = Db::name('startorfinishdata')->where(['Gcbh'=>$gcbh,'Status'=>$status])->find();
        if($data) {
            $this->error(__('报告信息已存在'));
        }


        //获取工程信息
        $gc1 = Db::name('zuoyedata')->where(['Gcbh'=>$gcbh])->find();
        Db::startTrans();
        try{
            Db::table('startorfinishdata')->insert(['Gcbh'=>$gcbh,'Sgdbh'=>$gc1['Sgdbh'],'Weidu'=>$weidu,'Jingdu'=>$jingdu,'Baogaodate'=>date("Y-m-d" ,strtotime( $date )),'Baogaotime'=>date("H:i:s" ,strtotime( $time )),'Zyrenwu'=>$gc1['Zyrenwu'],'Jhsdate'=>date("Y-m-d" ,strtotime( $date )),'Jhedate'=>date("Y-m-d" ,strtotime( $date )),'Inmans'=>$inmans,'Fzacky'=>'跨越架','Zxztky'=>$kuayue,'Fzacwl'=>'围栏','Zxztwl'=>$weilan,'Fzacfl'=>'封路','Zxztfl'=>$fenglu,'Fzacfh'=>'封河','Zxztfh'=>$fenghe,'Fzacno'=>'其他','Zxztno'=>$qita,'Tq'=>$tianqi,'Sqmd'=>$sqmd,'Status'=>$status,'Wz'=>$dan,'Dotsline'=>0,'Dotspass'=>0,'Dotspx'=>0]);
            Db::table('projectdata')->where(['Gcbh'=>$gcbh])->update(['gcstatus'=>$status,'gcbz'=>$gcbz]);
            Db::commit();   
        }catch (\Exception $e) {
            Db::rollback();
            $this->error(__('数据操作出错'));
        }
        $this->success('报告上传成功');
    }


     /**
    工程前三步(脱机)数据上传(解析后数据demo)
    $data = [
        //projectdata表关键字段
        'bh'   =>'S20200309104437_X20200903165427_W20200903165954',//managerid,Sgdbh
        'Gcbh' =>'20200903188888',//工程编号
        'Projectname'=>'88千伏吴江', //工程名称
        'datatime' => '2020-11-13 ', //工程日期 
        'ProjectType'=>'新建',//工程类别
        'linename'=>'吴江线',//线路名称
        //'jhdate'=>'2020-09-03 8:0~2020-09-03 20:0',//计划时间 开工时间~竣工时间 2020-09-03 8:0~2020-09-03 20:0
        'startdate'=>'2020-09-03 8:0',
        'enddate'=>'2020-09-03 20:0',
        'Projectadd'=>'吴江',//工程地址
        'Createman'=>'吴江作业队',//创建人
        //zuoyedata表关键字段
        //'xianqu'=>'吴江线', //xianqu,xiangzhen都是线路名称
        //zuoyesubdata 数据采集关键字段
        'subdata'=>[
            [
                'Gcbh'=>'20200903188888',//工程编号
                'ganhao'=>'吴江线_001',//杆塔号
                'Weidu'=>'39.8955321',//纬度
                'jingdu'=>'116.4077067',//经度
                'xuke'=>'Y',//许可点
                'caozuo'=>'Y',//操作点
                'jinzhi'=>'Y',//禁止点
                'duka'=>'Y',//危险点
                'kaiguan'=>'Y',//是否开关点
                'jiedi'=>'Y',//是否地线杆
                'zhixian'=>'N',//是否作业杆
                'jiaokua'=>'N',//是否交叉跨越点
                'bingxing'=>'N',//是否并行
                'lujing'=>'N',//是否班组地线杆
            ],
            [
                'Gcbh'=>'20200903188888',//工程编号
                'ganhao'=>'吴江线_002',//杆塔号
                'Weidu'=>'39.8951234',//纬度
                'jingdu'=>'116.4075678',//经度
                'xuke'=>'Y',//许可点
                'caozuo'=>'Y',//操作点
                'jinzhi'=>'Y',//禁止点
                'duka'=>'Y',//危险点
                'kaiguan'=>'N',//是否开关点
                'jiedi'=>'Y',//是否地线杆
                'zhixian'=>'N',//是否作业杆
                'jiaokua'=>'N',//是否交叉跨越点
                'bingxing'=>'N',//是否并行
                'lujing'=>'N',//是否班组地线杆
            ]
        ]
    ];

    */

    public function upload(){
        $jsondata  = $this->request->request("jsondata"); //json后的base64数据
        if(!$jsondata) {
            $this->error('未获取到工程脱机数据');
        }

        $data = json_decode(base64_decode($jsondata),true);
        if (!$data) {
            $this->error('工程脱机数据解析失败,请检查数据格式');
        }

        //检查工程编号是否存在与数据库
        $pd = Db::name('projectdata')->where('Gcbh',$data['Gcbh'])->find();
        if ($pd) {
            $this->error('当前工程编号已存在');
        }

        //查询终端设备编号
        $info = Db::name('basedata')->where(['Partntid'=>$data['bh'],'Datatype'=>'终端设备','Content1'=>'监控终端'])->field('Content2')->find();
        if(!$info) {
           $this->error('未获取到终端编号，写入失败');
        }

        //生成townid
        $tmp = explode('_', $data['bh']); //如果编号格式不会会引发异常
        $townid =  $tmp[0].'_'.$tmp[1];

        //开启事务处理       
        Db::startTrans();

        //将数据写入projectdata表
        $projectdata = [
            'townid'      => $townid,
            'managerid'   => $data['bh'],
            'Gcbh'        => $data['Gcbh'],
            'subbh'       => '000',
            'Sgdbh'       => $data['bh'],
            'Projectname' => $data['Projectname'],
            'datatime'    => $data['datatime'],
            'ProjectType' => $data['ProjectType'],
            'linename'    => $data['linename'],
            'jhdate'      => $data['startdate'].'~'.$data['enddate'],
            'Projectadd'  => $data['Projectadd'],
            'Createman'   => $data['Createman'],
            'gcstatus'    => '表单处理完毕,等待开工',
            'gcbz'        => '开'
        ];

        $projectdata_result = Db::name('projectdata')->insert($projectdata);

        //将数据写入zuoyedata表
        $zuoyedata = [
            'Gcbh'        => $data['Gcbh'],
            'Sgdbh'       => $data['bh'],
            'Pdabh'       => $data['bh'].'^0001',
            'datatime'    => $data['datatime'],
            'MainPdaip'   => $info['Content2'],
            'Senddate'    => $data['datatime'],
            'xianqu'      => $data['linename'],
            'xiangzhen'   => $data['linename'],
            'linename'    => $data['linename'],
            'Zyrenwu'     => $data['ProjectType'],
            'Jhstartdate'   => $data['startdate'],
            'Jhstarttime'   => $data['startdate'],
            'Jhenddate'   => $data['enddate'],
            'Jhendtime'   => $data['enddate'],
            'Inmans'     => 0,
            'Zypoints'   => 0,
            'status'    => '处理完毕'
        ];

        $zuoyedata_result = Db::name('zuoyedata')->insert($zuoyedata);

        //将数据写入zuoyesubdata表
        $zuoyesubdata_result = Db::name('zuoyesubdata')->insertall($data['subdata']);

        if (!$projectdata_result || !$zuoyedata_result || !$zuoyesubdata_result) {
            Db::rollback();
            $this->error('工程脱机数据写入失败');
        }

        Db::commit();
        $this->success('工程脱机数据写入成功');
    }   

    //强制挂接拆除
    public function hook_remove(){
        $lineid = $this->request->request("lineid");
        $gcbh = $this->request->request("gcbh");
        $jingdu = $this->request->request("jingdu");
        $weidu = $this->request->request("weidu");
        $types = $this->request->request("types");
        if (!$lineid||!$gcbh||!$jingdu||!$weidu||!$types) {
            $this->error(__('Invalid parameters'));
        }

        $line = Db::name('zuoyesubdata')->where(['id'=>$lineid])->find();
        $pda_work = Db::name('gc_pda_worker')->where(['gcbh'=>$gcbh,'datatype'=>'监控终端'])->find();
        if (!$line || !$pda_work) {
            $this->error('未查到杆塔信息');
        }
        $flag = '';
        $linetype = '';

        if($line['lujing'] == 'Y') {
            $linetype = '班组地线';
        }else {
            $linetype = '许可地线';
        }

        //插入数据
        if($types == "挂接") {
            $flag = 'line_on';
        }else {
            $flag = 'line_off';
        }
        date_default_timezone_set("Asia/Shanghai");
        $date0 = date("Y-m-d");
        $time0 = date("H:i:s");
 
        //写入数据
        //开启事务处理       
        Db::startTrans();
        $linedata = [
            'workerbh'=>$pda_work['workername'],
            'ganhao' => $line['ganhao'],
            'gcbh'=>$gcbh,
            'linedate'=>$date0,
            'linetime'=>$time0,
            'linebh'=>$pda_work['pdabh'],
            'linetype'=>$linetype,
            'linestatus'=>$types,
            'linelong'=>$line['jingdu'],
            'linelat'=>$line['Weidu'],
        ];
        $linedata_result =  Db::name('linedata')->insert($linedata);

        $apptempdata = [
            'gcbh'=>$gcbh,
            'flag'=>$flag,
            'status'=> 1,
            'txt'=>'地线OK$'.$line['ganhao'].'$'.$linetype.'$'.$types.'$'.$pda_work['workername'].'$'.$jingdu.'$'.$weidu.'$'.$date0.'$'.$time0
        ];
        $apptempdata_result =  Db::name('apptempdata')->insert($apptempdata);
        if (!$linedata_result || !$apptempdata_result ) {
            Db::rollback();
            $this->error('强制'.$types.'失败');
        }

        Db::commit();
        $this->success('强制'.$types.'成功');

    }
}